import requests
import numpy as np

import matplotlib.pyplot as plt

def getStockData():
    url = "https://api.mairui.club/hslt/list/b997d4403688d5e66a"  # 替换为实际的licence证书
    response = requests.get(url)
    data = response.json()

    # for stock in data[0:3]:
    #     print(f"股票代码：{stock['dm']}, 股票名称：{stock['mc']}, 交易所：{stock['jys']}")
    return data
    pass

"""
我有一个训练数组，每个元素都是股票一天的数据·
{
    'day': '2025-01-17',
    'open': '5.700',
    'high': '5.750',
    'low': '5.480',
    'close': '5.540',
    'volume': '417576753',
    'ma_price5': 5.722, 
    'ma_volume5': 473961433
}
遍历数组每次取索引开始的6个，前五个用来作为参数传入，第六个作为结果判断
8个字段*5个参数相当于是32个输入和

股票历史数组单元素字段	含义
{
    'day': '2025-01-17',
    'open': '5.700',
    'high': '5.750',
    'low': '5.480',
    'close': '5.540',
    'volume': '417576753',
    'ma_price5': 5.722, 
    'ma_volume5': 473961433
}
"""
def getHistoryData(code):
    url = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData"
    params = {
        "symbol": code,
        "scale": "240",  # 时间周期，如5分钟、日线等
        "ma": "5",
        "datalen": "1024"
    }
    response = requests.get(url, params=params)
    data = response.json()
    totalPrice = 0
    # for item in data:
        # totalPrice += float(item['close'])
        # print(f"日期：{item['d']}, 开盘价：{item['o']}, 最高价：{item['h']}, 最低价：{item['l']}, 收盘价：{item['c']}")
        # print(data)
    # totalPrice /= len(data)
    # print('totalPrice',totalPrice)
    return data


def calculate_mean_and_std(data):
    """
    计算均值和标准差
    :param data: list或numpy数组，包含过去一年的每日价格或回报率
    :return: 均值和标准差
    """
    mean = np.mean(data)
    std = np.std(data)
    return mean, std

def generate_signals(data, threshold=5):
    """
    根据均值回归策略生成买入和卖出信号
    :param data: list或numpy数组，包含过去一年的每日价格或回报率
    :param threshold: 阈值，表示标准差的倍数，默认为5
    :return: 买入信号和卖出信号的列表
    """
    mean, std = calculate_mean_and_std(data)
    buy_threshold = mean - threshold * std
    sell_threshold = mean + threshold * std

    buy_signals = []
    sell_signals = []

    for i, value in enumerate(data):
        if value < buy_threshold:
            buy_signals.append(i)  # 记录买入信号的索引
        elif value > sell_threshold:
            sell_signals.append(i)  # 记录卖出信号的索引

    return buy_signals, sell_signals, mean, std
def plot_signals(data, buy_signals, sell_signals):
    """
    绘制折线图并标记买入点和卖出点
    :param data: 股票价格数据
    :param buy_signals: 买入信号索引列表
    :param sell_signals: 卖出信号索引列表
    """
    plt.figure(figsize=(12, 6))
    plt.plot(data, label="Price", color="blue", alpha=0.7)

    # 标记买入点
    if buy_signals:
        plt.scatter(buy_signals, [data[i] for i in buy_signals], color="green", label="Buy Signal", marker="^", alpha=1)

    # 标记卖出点
    if sell_signals:
        plt.scatter(sell_signals, [data[i] for i in sell_signals], color="red", label="Sell Signal", marker="v", alpha=1)

    plt.title("Stock Price with Buy/Sell Signals")
    plt.xlabel("Time")
    plt.ylabel("Price")
    plt.legend()
    plt.grid(True)
    plt.show()
# 示例数据：假设这是过去一年的每日回报率
daily_returns = []
if __name__ == '__main__':
    stocks = getStockData()
    # print('stocks',stocks[0]['dm'])
    stocks = stocks[0:1]
    for stock in stocks:
        print(f"股票代码：{stock['dm']}, 股票名称：{stock['mc']}, 交易所：{stock['jys']}")
        hist = getHistoryData(f"{stock['jys']}{stock['dm']}")
        # hist = getHistoryData('sh601933')
        hist = hist[-30*1*12:-1 + 0 * 30]
        # print('hist',hist)
        for obj in hist:
            print('obj',obj['close'])
            daily_returns.append(float(obj['close']))
        # print('daily_returns',daily_returns)
        # 示例数据：假设这是过去一年的每日回报率（单位：百分比）
        # daily_returns = np.random.normal(loc=0.01, scale=0.05, size=252)  # 生成随机回报率数据

        # 计算均值和标准差
        mean, std = calculate_mean_and_std(daily_returns)
        print(f"均值 (Mean): {mean:.4f}")
        print(f"标准差 (Standard Deviation): {std:.4f}")

        # 生成信号
        buy_signals, sell_signals, _, _ = generate_signals(daily_returns, threshold=1.2)
        print(f"买入信号 (Buy Signals) 索引: {buy_signals}")
        print(f"卖出信号 (Sell Signals) 索引: {sell_signals}")
        # 绘制图表
        plot_signals(daily_returns, buy_signals, sell_signals)
        
